package com.lianniu.web.buyerOrder.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.lianniu.web.base.BaseResult;
import com.lianniu.web.buyerOrder.dao.IBuyerOrderDao;
import com.lianniu.web.buyerOrder.model.BuyerOrderConditionVo;
import com.lianniu.web.buyerOrder.model.CancelOrder;
import com.lianniu.web.buyerOrder.model.OrderDetailVo;
import com.lianniu.web.buyerOrder.model.OrderInfoVo;
import com.lianniu.web.buyerOrder.service.IBuyerOrderService;
import com.lianniu.web.buyerProduct.dao.IBuyerInfoDao;
import com.lianniu.web.buyerProduct.dao.ICartDao;
import com.lianniu.web.buyerProduct.model.BuyerInfoVo;
import com.lianniu.web.constants.ErrorCode;
import com.lianniu.web.product.dao.ISkuProductDao;
import com.lianniu.web.product.model.SkuProductVo;
import com.lianniu.web.util.StringUtil;

@Service
public class BuyerOrderServiceImpl implements IBuyerOrderService {

    private static final Logger logger = LoggerFactory.getLogger(BuyerOrderServiceImpl.class);
    @Autowired
    IBuyerOrderDao buyerOrderDao;
    @Autowired
    ICartDao cartDao;
    @Autowired
    IBuyerInfoDao buyerInfoDao;

    @Autowired
    ISkuProductDao skuProductDao;

    @Override
    public BaseResult getOrderInfo(String orderid) {
        if (StringUtil.isEmpty(orderid)) {
            logger.info("orderid 为空，返回错误");
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        logger.info(String.format("获取订单%s订单详情", orderid));
        OrderInfoVo orderInfoVo = buyerOrderDao.getOrderById(orderid);
        logger.info("获取到的订单详情为：" + JSON.toJSONString(orderInfoVo));
        return BaseResult.success(orderInfoVo);
    }

    @Override
    public BaseResult getOrders(BuyerOrderConditionVo condition) {
        logger.info("获取卖家订单列表,condition=" + JSON.toJSONString(condition));
        if (StringUtils.isBlank(condition.getUserId())) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        List<OrderInfoVo> buyerOrders = buyerOrderDao.getOrders(condition);
        logger.info("获取到的订单列表为：" + JSON.toJSONString(buyerOrders));
        return BaseResult.success(buyerOrders);
    }

    @Override
    @Transactional
    public BaseResult cancelOrder(CancelOrder cancel) {
        logger.info("取消订单：" + JSON.toJSONString(cancel));
        if (StringUtils.isBlank(cancel.getOrderid()) || StringUtils.isBlank(cancel.getUserid())
                || StringUtils.isBlank(cancel.getCancelReason())) {
            logger.info("有参数为空，直接返回失败");
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        if (cancel.getCancelReason().length() > CancelOrder.CANCEL_REASON_MAX_LENGTH) {
            logger.info("取消原因长度过长：" + cancel.getCancelReason().length());
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        
        if(buyerOrderDao.cancelOrder(cancel)&&buyerOrderDao.cancelOrderDetail(cancel)){
            skuProductDao.addOverPlusNumBySkuId(cancel.getOverPlusNum(), cancel.getSkuId());
            return BaseResult.success();
        }
        return BaseResult.exception("数据库更新异常");
    }

    @Override
    public BaseResult payMoney(CancelOrder pay) {
        logger.info("支付信息：" + pay);
        if (StringUtils.isBlank(pay.getOrderid()) || StringUtils.isBlank(pay.getUserid())) {
            logger.info("有参数为空，直接返回失败");
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                    ErrorCode.ParaCheckErrorRetInfo);
        }
        buyerOrderDao.payMoney(pay);
        buyerOrderDao.payMoneyDetail(pay);
        return BaseResult.success();
    }

    @Override
    public BaseResult confirmOrder(CancelOrder confirm) {
        logger.info("确认收货" + confirm);
        buyerOrderDao.confirmOrder(confirm);
        buyerOrderDao.confirmOrderDetail(confirm);
        return BaseResult.success();
    }

    @Override
    public BaseResult sureOrder(CancelOrder sure) {
        logger.info("改变评价状态" + sure);
        buyerOrderDao.sureOrder(sure);
        buyerOrderDao.sureOrderDetail(sure.getOrderid());
        return BaseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class )
    public BaseResult addOrder(OrderInfoVo order) {
        logger.info("BuyerOrderServiceImpl getOrderCode begin");
        StringBuffer orderCodes = new StringBuffer();
        Map<String, Object> map = new HashMap<>();
        map.put("paramStr", "LN");
        map.put("paramInt", 8);
        map.put("retStr", "");
        List<OrderDetailVo> l = order.getLstOrderDetail();
        Set<String> set = new HashSet<>();
        if(l.size()>0){
            for(int i =0;i<l.size();i++){
                set.add(l.get(i).getSupplyID());
            }
        }
        List<OrderInfoVo> ol = new ArrayList<>();
        if(set.size()>0){
            for(String ss:set){
                OrderInfoVo oiv = new OrderInfoVo();
                oiv.setConsAddr(order.getConsAddr());
                oiv.setUserId(order.getUserId());
                oiv.setConsignee(order.getConsignee());
                oiv.setConsMobile(order.getConsMobile());
                List<OrderDetailVo> l1 = new ArrayList<>();
                if(l.size()>0){
                    for(int i =0;i<l.size();i++){
                        if(ss.equals(l.get(i).getSupplyID())){
                            l1.add(l.get(i));
                        }
                    }
                }
                double d = 0;
                if(l1.size()>0){
                    for(OrderDetailVo o:l1){
                        d = d + Double.parseDouble(o.getPrice());
                    }
                }
                oiv.setLstOrderDetail(l1);
                oiv.setPrice(d+"");
                ol.add(oiv);
            }
        }
        
        List<SkuProductVo> skuList = new ArrayList<>();
        List<OrderDetailVo> list = new ArrayList<>();
        if(ol.size()>0){
            for(OrderInfoVo order1:ol){
                String orderCode = buyerOrderDao.getOrderCode(map);
                order1.setOrderCode(orderCode);
                order1.setAddTime(new Date());
                order1.setAddUser(order1.getUsersName());
                order1.setPayType(order.getPayType());
                order1.setShipStatus("00");
                order1.setConsStatus("");
                order1.setOrderSource("2");
                order1.setOrderStatus("01");
                order1.setOrderType("");
                order1.setDelFlag("1");
                order1.setRemark(order.getRemark());
                order1.setPreRecvTime(order.getPreRecvTime());
                SkuProductVo spv = skuProductDao.getSkuProductById(order1.getLstOrderDetail().get(0).getSupplyProductID());
                if (spv.getOverPlusNum() < Double.valueOf(order1.getLstOrderDetail().get(0).getProductNum())) {
                    throw new RuntimeException("库存不足");
                }
                order1.setStaffId(spv.getStaff1Id());
                buyerOrderDao.addOrderInfo(order1);
                orderCodes.append(order1.getId()+",");
                if (null != order1.getLstOrderDetail()) {
                    for (int i = 0; i < order1.getLstOrderDetail().size(); i++) {
                        SkuProductVo skuProductVo = new SkuProductVo();
                        order1.getLstOrderDetail().get(i).setOrderID(order1.getId());
                        order1.getLstOrderDetail().get(i).setOrderStatus(order1.getOrderStatus());
                        order1.getLstOrderDetail().get(i).setShipStatus(order1.getShipStatus());
                        order1.getLstOrderDetail().get(i).setAddTime(new Date());
                        order1.getLstOrderDetail().get(i).setAddUser(order1.getAddUser());
                        order1.getLstOrderDetail().get(i).setDelFlag("1");
                        skuProductVo.setId(order1.getLstOrderDetail().get(i).getSupplyProductID());
                        skuProductVo.setOverPlusNum(
                                Double.parseDouble(order1.getLstOrderDetail().get(i).getProductNum()));
                        skuList.add(skuProductVo);
                        list.add(order1.getLstOrderDetail().get(i));
                    }
                } 
            }
        }
        buyerOrderDao.addOrderDetail(list);
        if (order.getCartId() != null && !"".equals(order.getCartId())) {
            String[] cartIds = order.getCartId().split(",");
            cartDao.delete(cartIds);
        }
        /*for (int n = 0; n < skuList.size(); n++) {
            skuProductDao.reduceOverPlusNumBySkuId(skuList.get(n).getOverPlusNum(),
                    skuList.get(n).getId());
        }*/
        int i = skuProductDao.reduceOverPlusNum(skuList);
        if (i <= 0) {
            throw new RuntimeException("库存不足");
        }
        logger.info("BuyerOrderServiceImpl getOrderCode end");
        return BaseResult.success(ol);
    }

    @Override
    public BaseResult getCode(String prefix,int len) {
        Map<String, Object> map = new HashMap<>();
        map.put("paramStr", prefix);
        map.put("paramInt", len);
        map.put("retStr", "");
        String orderCode = buyerOrderDao.getOrderCode(map);
        return BaseResult.success(orderCode);
    }
    @Override
    public BaseResult getBuyerInfo(String userId) {
        logger.info("BuyerOrderServiceImpl getBuyerInfo end");
        BuyerInfoVo buyerInfoVo = buyerInfoDao.getBuyerInfoByUserId(userId);
        BaseResult result = BaseResult.success(buyerInfoVo);
        logger.info("BuyerOrderServiceImpl getBuyerInfo end");
        return result;
    }
    @Override
    public BaseResult changeName(String userId,String buyerName){
        boolean result = this.buyerOrderDao.changeBuyerName(userId,buyerName);
        return BaseResult.success(result);
    }
}
